package gradle.common.feign.config.exception;

import gradle.common.core.enums.ResultCodeEnum;
import gradle.common.core.response.BaseResponse;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ResponseBody
@ControllerAdvice("org.example")
public class SecurityExceptionHandler {

    /**
     * 是否打印堆栈给前端
     */
    @Value("${response.traceException:false}")
    private boolean traceException;

    /**
     * 权限不足已隐藏
     *
     * @param response 响应
     * @param e        异常
     * @return 标准返回值
     */
    @ExceptionHandler(PermissionException.class)
    public BaseResponse permissionExceptionHandler(HttpServletResponse response, Exception e) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        log.error(e.getMessage(), e);
        return new BaseResponse(ResultCodeEnum.UNAUTHORIZED.getCode(), this.getExceptionMessage(e, ResultCodeEnum.UNAUTHORIZED), this.getTrackExceptionMessage(e));
    }

    /**
     * 获取异常描述
     *
     * @param e 异常
     * @return 异常 Message
     */
    private String getExceptionMessage(Exception e, ResultCodeEnum resultCodeEnum) {
        if (this.traceException) {
            return e.getMessage();
        }
        return resultCodeEnum.getMessage();
    }

    /**
     * 获取异常堆栈
     *
     * @param e 异常
     * @return 异常堆栈信息
     */
    private String getTrackExceptionMessage(Exception e) {
        if (this.traceException) {
            return ExceptionUtils.getStackTrace(e);
        }
        return "";
    }


}
